package com.project.interceptor;

import cn.hutool.json.JSONUtil;
import com.project.common.RedisConstants;
import com.project.common.UserHolder;
import com.project.entity.redis.UserInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.project.common.RedisConstants.LOGIN_STUDENT_TTL;
import static com.project.common.RedisConstants.ONLINE_STUDENTLIST_KEY;


public class RefreshTokenInterceptor implements HandlerInterceptor {


    //    @Resource 不能使用注解进行注入
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor() {
    }

    //使用构造器注入
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1,获取请求头中的token
        String token = request.getHeader("token");

        if (token == null) {
            return true;
        }
        //2.获取redis中的用户信息
        String key = RedisConstants.LOGIN_USER_KEY + token;

        String userJson = stringRedisTemplate.opsForValue().get(key);
        //3.判断用户是否存在
        if (userJson==null) {
            return true;
        }

        //5.存在，保存用户信息到ThreadLocal
        //将json转为对象存储到ThreadLocal
        UserInfo user2 = JSONUtil.toBean(userJson, UserInfo.class);




        if(user2.getType().equals("user")){



            String onlineStudentListKey=ONLINE_STUDENTLIST_KEY;
            //如果是普通用户类型,更新zset该元素的在线时间
            long nowOnlineTime = new Date().getTime();
            //添加进去
            stringRedisTemplate.opsForZSet().add(ONLINE_STUDENTLIST_KEY,userJson,nowOnlineTime);


            //6,刷新token的有效期--String类型
            stringRedisTemplate.expire(key,LOGIN_STUDENT_TTL,TimeUnit.MINUTES);
        }else{
            //6,刷新管理员token的有效期--String类型
//            stringRedisTemplate.expire(key,LOGIN_ADMIN_TTL,TimeUnit.MINUTES);
        }


        //7.放行
        UserHolder.saveUser(user2);
        return true;

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //请求结束，移除用户,防止内存泄漏
        UserHolder.removeUser();
    }
}
